<?php
/**
 * User: Hufeng
 * Date: 2017/08/29 19:48
 * Desc: 用户Model
 */
namespace App\Model;
use SasPHP\SqlModel;

class UserAddressModel extends SqlModel{
    protected $dbName = 'user_address';

    public function __construct(){
        parent::__construct('DB_SERVER');
    }

    function insertData($data){
        $this->dbConn->insert($this->dbName,$data);
        return $this->dbConn->id();
    }

    function editData($where,$data){
        $this->dbConn->update($this->dbName,$data,$where);
    }

    function delData($data){
        $this->dbConn->delete($this->dbName, $data);
    }

    function findData($where,$fields='*'){
        $res = $this->dbConn->get($this->dbName,$fields,$where);
        return $res;
    }

    function queryData($where,$fields='*'){
        $res = $this->dbConn->select($this->dbName,$fields,$where);
        return $res;
    }
    //获取统计数据
    public function getTotalNum($where){
        $res = $this->dbConn->count($this->dbName,$where);
        return $res;
    }
    //sum数据
    public function sumData($where,$param){
        $res = $this->dbConn->sum($this->dbName,$param,$where);
        return $res;
    }

    //增加资产
    function addAssets($uid,$money,$type,$status,$memo){
        $money = round($money,2);
        $res = $this->findData(['uid'=>$uid,'type'=>$type,'status'=>$status],['money']);
        //更新用户总资产
        if(!$res){
            $leftMoney = $money;
            $uaData = ['uid'=>$uid,'money'=>$leftMoney,'type'=>$type,'status'=>$status];
            $this->insertData($uaData);
        }else{
            $leftMoney = $res['money']+$money;
            $where = ['id'=>$res['id']];
            $uaData = ['money'=>$leftMoney];
            $this->editData($where,$uaData);
        }
        //记录用户资产明细
        $ualModel = new UserAssetsLogModel();
        $ualData = [
            'uid'=>$uid,
            'change_money'=>$money,
            'left_money'=>$leftMoney,
            'type'=>$type,
            'status'=>$status,
            'addtime'=>date('Y-m-d H:i:s'),
            'memo'=>$memo
        ];
        $ualModel->insertData($ualData);
        return true;
    }
    //扣减资产
    function reduceAssets($uid,$money,$type,$status,$memo){
        $money = round($money,2);
        $res = $this->findData(['uid'=>$uid,'type'=>$type,'status'=>$status],['money']);
        if($res['money']<$money){
            return false;
        }
        //更新用户总资产
        $leftMoney = round($res['money']-$money,2);
        $where = ['id'=>$res['id']];
        $uaData = ['money'=>$leftMoney];
        $this->editData($where,$uaData);

        //记录用户资产明细
        $ualModel = new UserAssetsLogModel();
        $ualData = [
            'uid'=>$uid,
            'change_money'=>-$money,
            'left_money'=>$leftMoney,
            'type'=>$type,
            'status'=>$status,
            'addtime'=>date('Y-m-d H:i:s'),
            'memo'=>$memo
        ];
        $ualModel->insertData($ualData);
        return true;
    }
}
